<?php


namespace App\Services;


use App\Utils\Code;
use Illuminate\Http\Request;
use Storage;

class FileService extends BaseService
{
    /**
     * 文件上传
     * @param Request $request
     * @param string $disk
     * @param null $bucket
     * @param bool $datePath
     * @return array
     * @throws \Exception
     */
    public function upload(Request $request, $disk = 'public', $bucket = null, $datePath = true) {
        // 设置上传空间
        $disk = $request->input('disk', $disk);
        // 获取文件数组
        $files = $request->file('files');
        if (!$files && !$files = $request->file('file')) {
            throw new \Exception('没有上传任何文件', Code::PARAMETER_ERROR);
        } else {
            $files = is_array($files) ? $files : [$files];
        }
        // 循环上传文件
        $response = [];
        $path = $datePath ? date('Y/m/d') : '';
        foreach ($files as $file) {
            if ($disk == 'public' && !$bucket) {
                // 获取文件类型
                $fileType = $file->extension();
                if (in_array($fileType, ['jpg', 'jpeg', 'png'])) {
                    $bucket = 'images';
                } elseif (in_array($fileType, ['crt','cert'])) {
                    $bucket = 'cert';
                } else {
                    $bucket = 'images';
                }
                $response[] = Storage::url($file->store($bucket . '/' . $path, ['disk'=>$disk]));
            } else {
                $response[] = $file->store($bucket . '/' . $path, ['disk'=>$disk]);
            }
        }
        return $response;
    }
}
